import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card, Col, Tabs,message,Divider,Tooltip,Row} from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';
import {InfoCircleOutlined} from '@ant-design/icons';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const {TabPane} = Tabs;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  imageValues: any
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate,dataFormValues,imageValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureVideo, setPictureVideo] = useState<any[]>([]);
  const [uploadVideoChanged, setUploadVideoChanged] = useState<boolean>(false);
  const [pictureAudio, setPictureAudio] = useState<any[]>([]);
  const [uploadAudioChanged, setUploadAudioChanged] = useState<boolean>(false);
  const [pictureFile, setPictureFile] = useState<any[]>([]);
  const [uploadFileChanged, setUploadFileChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  // const [dataFormValues, setDataFormValues] = useState({});
  const [activeTabKey, setActivityKey] = useState<any>('1');

  const okFileHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      
      console.log("submit fields ", fieldsValue)

      var submitValue = [
        {
          //请求当前一组配置参数，tag=storageDocs
          "alias_key": 'storageDocs',
          "item_type":'system',
          "dict_item_arr": [
            {
              "alias_key": "docs_service",
              "item_value": fieldsValue.docs_service,
              'item_type':"select",
            },
            {
              "alias_key": "docs_secret_id",
              "item_value": fieldsValue.docs_secret_id,
              'item_type':"text",
            },
            {
              "alias_key": "docs_secret_key",
              "item_value": fieldsValue.docs_secret_key,
              'item_type':"text",
            },
            {
              "alias_key": "docs_bucket_name",
              "item_value":fieldsValue.docs_bucket_name,
              'item_type':"text",
            },
            {
              "alias_key": "docs_bucket_area",
              "item_value": fieldsValue.docs_bucket_area,
              'item_type':"text",
            },
            {
              "alias_key": "docs_bucket_domain",
              "item_value": fieldsValue.docs_bucket_domain,
              'item_type':"url",
            },
            {
              "alias_key": "docs_ext",
              "item_value": fieldsValue.docs_ext,
              'item_type':"text",
            },
            {
              "alias_key": "docs_max_size",
              "item_value": fieldsValue.docs_max_size,
              'item_type':"number",
            },
            {
              "alias_key": 'docs_url_status',
              "item_value": fieldsValue.docs_url_status,
              'item_type': "radio",
            },
            {
              "alias_key": "docs_url_key",
              "item_value":fieldsValue.docs_url_key,
              'item_type':"text",
            },
            {
              "alias_key": "docs_url_expire",
              "item_value": fieldsValue.docs_url_expire,
              'item_type':"text",
            },
            {
              "alias_key": "docs_online_preview",
              "item_value": fieldsValue.docs_online_preview,
              'item_type':"text",
            },
            {
              "alias_key": "docs_preview_ext",
              "item_value": fieldsValue.docs_preview_ext,
              'item_type':"text",
            },
          ]
        }
    ]
    // 如果更新成功之后，重置表单
    updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
      console.log('handleSubmit then success is ', JSON.stringify(submitValue))
      if(res.code == 0){
        message.success('保存成功');
        // form.resetFields()
      }
    })
    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      // setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置视频图片上传文件值
    const setVideoUploadFile = (fileList:any) => {
      setUploadVideoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureVideo(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureVideo([])
      }
    }
    // 设置视频图片上传文件值
    const setAudioUploadFile = (fileList:any) => {
      setUploadVideoChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureAudio(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureAudio([])
      }
    }
    // 设置视频图片上传文件值
    const setFileUploadFile = (fileList:any) => {
      setUploadFileChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureFile(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureFile([])
      }
    }

    const parseData = (key:any,options:any) => {
      // console.log(options);
      var name:any = "";
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            name = item?.item_value;
          }
        })
      }
      return name
    }


  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(parseData('repair_image',imageValues))
  const defaultVideoPicture = DataHelper.buildFileByUrl(parseData('repair_video',imageValues))
  const defaultAudioPicture = DataHelper.buildFileByUrl(parseData('repair_audio',imageValues))
  const defaultFilePicture = DataHelper.buildFileByUrl(parseData('repair_doc',imageValues))

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadVideoButton = DataHelper.showUploadBtn(isUpdate, pictureVideo, defaultVideoPicture, uploadVideoChanged)
  const showUploadAudioButton = DataHelper.showUploadBtn(isUpdate, pictureAudio, defaultAudioPicture, uploadAudioChanged)
  const showUploadFileButton = DataHelper.showUploadBtn(isUpdate, pictureFile, defaultFilePicture, uploadFileChanged)

  // 弹出框
  // @ts-ignore
  return <div>
    <Card title={'存储设置'} className={styles.card} bordered={false}>
      <Row gutter={16}>
        <Col lg={6} md={12} sm={24}>
          <FormItem label={'存储服务商'}>
            {form.getFieldDecorator('docs_service', {
              initialValue: parseData('docs_service',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Select placeholder={"应用市场可以安装更多服务商"} size={'default'} style={{ width: '100%' }}>
            {common.fileOption && TsxHelper.buildSelectOption(common.fileOption)}
          </Select>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
          <FormItem label={'Secret ID'}>
            {form.getFieldDecorator('docs_secret_id', {
              initialValue: parseData('docs_secret_id',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
          <FormItem label={'Secret Key'}>
            {form.getFieldDecorator('docs_secret_key', {
              initialValue: parseData('docs_secret_key',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
          </FormItem>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col lg={6} md={12} sm={24}>
          <FormItem label={'存储配置名称'}>
            {form.getFieldDecorator('docs_bucket_name', {
              initialValue: parseData('docs_bucket_name',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
          <FormItem label={
              <span>
                <FormattedMessage id="存储配置地域" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="存储配置地域，用不到则留空" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
            {form.getFieldDecorator('docs_bucket_area', {
              initialValue: parseData('docs_bucket_area',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={"用不到则留空"}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
          <FormItem label={
              <span>
                <FormattedMessage id="存储配置域名" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="存储配置域名以 http:// 或 https:// 开头，结尾不带 /" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
            {form.getFieldDecorator('docs_bucket_domain', {
              initialValue: parseData('docs_bucket_domain',dataFormValues),
              rules: [{ pattern: /(http|https):\/\/([\w.]+\/?)\S*(?<![/])$/, message: '请输入合法域名'}],
            })(<Input placeholder={'http:// 或 https:// 开头，结尾不带 /'}/>)}
          </FormItem>
        </Col>
      </Row>
    </Card>

    <Card title={'功能配置'} className={styles.card} bordered={false}>
      <Row gutter={16}>
        <Col lg={6} md={12} sm={24}>
          <FormItem label={'支持的扩展名'} >
            {form.getFieldDecorator('docs_ext', {
              initialValue: parseData('docs_ext',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={"以英文逗号 , 隔开"}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
          <FormItem 
          label={
            <span>
              <FormattedMessage id="支持的最大尺寸" />
              <em className={styles.optional}>
                <Tooltip title={<FormattedMessage id="如果用户角色有单独设置将以用户角色为准" />}>
                  <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                </Tooltip>
              </em>
            </span>
          }>
            {form.getFieldDecorator('docs_max_size', {
              initialValue: parseData('docs_max_size',dataFormValues),
              rules: [{ pattern: /^[0-9]*$/, message: '请输入合理的尺寸大小' }],
            })(<Input addonAfter="MB" placeholder={""} style={{width:'100%'}}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
          
        </Col>
      </Row>
      <Row gutter={16}>
        <Col lg={6} md={12} sm={24}>
          <FormItem 
            label={
              <span>
                <FormattedMessage id="防盗链功能" />
                <em className={styles.optional}>
                  <Tooltip title={<FormattedMessage id="如果插件不支持防盗链功能，请勿开启，否则将导致资源无法访问" />}>
                    <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                  </Tooltip>
                </em>
              </span>
            }>
              {form.getFieldDecorator('docs_url_status', {
                initialValue: parseData('docs_url_status',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>关闭</Radio>
              <Radio value={true}>开启</Radio>
              {/* {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)} */}
            </Radio.Group>)}
          </FormItem>
        </Col>
        {form.getFieldValue("docs_url_status") == true && <>
        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
          <FormItem 
          label={
            <span>
              <FormattedMessage id="防盗链 Key" />
              <em className={styles.optional}>
                <Tooltip title={<FormattedMessage id="用于生成访问 Token" />}>
                  <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                </Tooltip>
              </em>
            </span>
          }>
            {form.getFieldDecorator('docs_url_key', {
              initialValue: parseData('docs_url_key',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={""}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
          <FormItem label={'防盗链签名有效期'}>
            {form.getFieldDecorator('docs_url_expire', {
              initialValue: parseData('docs_url_expire',dataFormValues),
              rules: [{ pattern: /^[0-9]*$/, message: '请输入合理的有效期' }],
            })(<Input addonAfter="分钟" placeholder={""} style={{width:'100%'}}/>)}
          </FormItem>
        </Col>
        </>
        }
      </Row>

      <Row gutter={16}>
        <Col lg={6} md={12} sm={24}>
          <FormItem label={
            <span>
              <FormattedMessage id="在线预览配置" />
              <em className={styles.optional}>
                <Tooltip title={<FormattedMessage id="输入框任意一个留空，均代表不开启预览功能。文件地址变量名 {file}" />}>
                  <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                </Tooltip>
              </em>
            </span>
          } >
            {form.getFieldDecorator('docs_online_preview', {
              initialValue: parseData('docs_online_preview',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={"留空代表未开启"}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
          <FormItem label={'在线预览扩展名'}>
            {form.getFieldDecorator('docs_preview_ext', {
              initialValue: parseData('docs_preview_ext',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Input placeholder={'支持在线预览的文件扩展名'}/>)}
          </FormItem>
        </Col>
        <Col xl={{ span: 8, offset: 2 }} lg={{ span: 10 }} md={{ span: 24 }} sm={24}>
          
        </Col>
      </Row>
    </Card>
    <Col span={24}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okFileHandle()}}>保存</Button>
      </div>
    </Col>
    
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </div>;
};

export default Form.create<DataFormProps>()(DataForm);
